<template>
	<view class="pagination-bar pc">
		<!-- #ifdef H5 -->
		<view class="pagination">
			<button class="link" :class="{'disabled': current == 1}" @click="setCurrent(current - 1)"> « </button>
			<button class="link" :class="{'disabled': current == 1}" @click="setCurrent(1)"> 首 </button>
			<button class="link" :class="{'active': current == item.val}" v v-for="(item, index) in grouplist" :key="index"
			 @click="setCurrent(item.val)">{{item.text}}</button>
			<button class="link" :class="{'disabled': current == page}" @click="setCurrent(page)"> 尾 </button>
			<button class="link" :class="{'disabled': current == page}" @click="setCurrent(current + 1)"> » </button>
		</view>
		<!-- #endif -->
	</view>
</template>

<script>
	export default {
		props: {
			page: { // 总页数
				type: Number,
				default: 10
			},
			num: { // 当前页码
				type: Number,
				default: 1
			},
			pagegroup: { // 分页条数
				type: Number,
				default: 5
			}
		},
		data() {
			return {
				current: this.num
			}
		},
		name: 'uni-pagination',
		computed: {
			grouplist: function() { // 获取分页页码
				let len = this.page, //总页数
					temp = [], //临时分组
					list = [], //列表
					count = Math.floor(this.pagegroup / 2), //分页条数
					center = this.current //当前页
				if (len <= this.pagegroup) {
					while (len--) {
						temp.push({
							text: this.page - len,
							val: this.page - len
						})
					}
					return temp
				}
				while (len--) {
					temp.push(this.page - len)
				}
				let idx = temp.indexOf(center)
					(idx < count) && (center = center + count - idx)
					(this.current > this.page - count) && (center = this.page - count)
				temp = temp.splice(center - count - 1, this.pagegroup)
				do {
					let t = temp.shift()
					list.push({
						text: t,
						val: t
					})
				} while (temp.length) //数组合并?
				if (this.page > this.pagegroup) {
					(this.current > count + 1) && list.unshift({
							text: '...',
							val: list[0].val - 1
						})
						(this.current < this.page - count) && list.push({
							text: '...',
							val: list[list.length - 1].val + 1
						})
				}
				return list
			}
		},
		methods: {
			setCurrent: function(idx) {
				if (this.current != idx && idx > 0 && idx < this.page + 1) {
					this.current = idx
					this.$emit('pagechange', this.current)
				}
			}
		}
	}
</script>

<style lang="scss">
	/* #ifdef H5 */
	@media screen and (min-width: 750px) {
		.pagination {
			display: flex;
			justify-content: center;
			margin-top: 30px;
			margin-bottom: 30px;
			height: 40px;

			.link {
				margin: 0 5px;
				color: #666;
				display: block;
				width: 40px;
				height: 40px;
				text-align: center;
				line-height: 40px;
				font-size: 14px;
				border-radius: 5px;

				&:hover {
					background-color: $base-color-pc;
					color: #fff;
				}
			}

			.active {
				background-color: $base-color-pc;
				color: #fff;
			}
		}
	}

	/* #endif */
</style>
